package com.esen.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blade.ioc.annotation.Bean;
import com.esen.dbpool.DataSourceFactory;
import com.esen.service.UserService;
import com.github.drinkjava2.jdialects.Dialect;
import com.github.drinkjava2.jdialects.model.TableModel;

@Bean
public class UserServiceImpl implements UserService {
	private static final Logger SLF4J = LoggerFactory.getLogger(UserServiceImpl.class);

	/****
	 * 通过构造id和password来实现SQL注入
	 * <pre>
	 * 构造输入参数id：user1' OR '1=1' -- ,password值为password1
	 * 构造参数id:user1,password值为：aa' OR '1=1
	 * 构造参数id：admin'; --'
	 * </pre>
	 * {@inheritDoc}
	 */
	public boolean login(String id, String password) throws Exception {
		String sql = "select * from t_users where id='" + id + "' AND password='" + password + "'";
		SLF4J.error("Login SQL:" + sql);
		Connection conn = DataSourceFactory.getConnection();
		try {
			Statement stmt = conn.createStatement();
			try {
				ResultSet rs = stmt.executeQuery(sql);
				try {
					if (rs.next()) {
						return true;
					}
				} finally {
					rs.close();
				}
			} finally {
				stmt.close();
			}
		} finally {
			conn.close();
		}
		return false;
	}

	public void initData() throws Exception {
		Connection conn = DataSourceFactory.getConnection();
		try {
			Dialect d = Dialect.guessDialect(conn);
			TableModel model = new TableModel("t_users");
			model.addColumn("id").STRING(30);
			model.addColumn("password").STRING(30);
			String[] dropSQL = d.toDropDDL(model);
			String[] createSQL = d.toCreateDDL(model);
			for (String sql : dropSQL) {
				executeSQL(conn, sql);
			}
			for (String sql : createSQL) {
				executeSQL(conn, sql);
			}
			for (int i = 0; i < 10; i++) {
				StringBuilder sb = new StringBuilder(1024).append("INSERT INTO t_users (id,password) VALUES ('user").append(
						i).append("','password").append(i).append("')");
				executeSQL(conn, sb.toString());
			}
		} finally {
			conn.close();
		}
	}

	private void executeSQL(Connection conn, String sql) throws Exception {
		Statement stmt = conn.createStatement();
		try {
			stmt.executeUpdate(sql);
		} finally {
			stmt.close();
		}
	}

	
	/***
	 * 构造password：111';drop table t_users;--'  id随便传
	 * {@inheritDoc}
	 */
	public void uddatePassword(String id, String password) throws Exception {
		String sql = "update t_users set password = '" + password + "' where id='" + id + "'";
		SLF4J.error("Update SQL:" + sql);
		Connection conn = DataSourceFactory.getConnection();
		try {
			Statement stmt = conn.createStatement();
			try {
				stmt.executeUpdate(sql);
			} finally {
				stmt.close();
			}
		} finally {
			conn.close();
		}
	}

}
